package org.leaf.green.b2b

import org.leaf.green.admin.RecordType

import org.springframework.transaction.annotation.*

import org.codehaus.groovy.grails.web.metaclass.BindDynamicMethod

class PurchaseService {

    static transactional = true

    //record type
    @Transactional(readOnly = true)
    def recordType() {
        log.info("recordType")
        def recordType_purchase = RecordType.withCriteria(uniqueResult:true){
            projections{
                property('id')
            }
            eq("domain", "purchase")
            eq("serialNumber", "1")
        }
        log.info("recordType_purchase=${recordType_purchase}")
        return recordType_purchase
    }    

    @Transactional(readOnly = true)
    def list(Object params) {
        log.info("list_purchase")
        def recordType_purchase = this.recordType()
        
        def purchaseInstanceList = Purchase.withCriteria{
            eq("recordType.id", recordType_purchase)
            if(params?.max) maxResults(params.int('max'))
			if(params?.offset) firstResult(params.int('offset'))
			if(params?.sort && params?.order) order(params?.sort, params?.order)
            order("id", "asc")
        }

        return purchaseInstanceList
    }

    @Transactional(readOnly = true)
    def count() {
        log.info("count_purchase")
        def recordType_purchase = this.recordType()

        def purchaseInstanceCount =  Purchase.withCriteria{
            count("id")
            eq("recordType.id", recordType_purchase)
       }
        return purchaseInstanceCount
    }

    //init purchase
    def initPurchase(Object params){
        //new
        def purchaseInstance = new Purchase()
        //set record type
        BindDynamicMethod mybind = new BindDynamicMethod()
        def mymap = ['recordType.id' : this.recordType()]
        def myargs =  [purchaseInstance, mymap]
        mybind.invoke(purchaseInstance, 'bind', (Object[]) myargs)
        //add details
        def begin_serialNumber = 0
        Product.listOrderBySerialNumber().each{ product ->
            begin_serialNumber += 1
            purchaseInstance.addToDetails(
                new PurchaseDetail(
                      serialNumber : String.format('%03d', begin_serialNumber)
                    , product : product
                    , dealer : null
                    , quantity : 0
                    , unit : '斤'
                )
            )
        }
        //set serialnumber
        purchaseInstance.serialNumber = "${new Date().format('yyyyMMdd')}000"
        return purchaseInstance
    }
}
